/**
 * 下面案例，去掉函数的 async 和 await，变成纯函数，同步调用，也能在task2函数中输出请求后的结果？怎么实现
 */

// function getData() {
//   return fetch("https://sponsors.vuejs.org/data.json").then((res) => {
//     return res.json().then((res) => res);
//   });
// }

// async function task1() {
//   const res = await getData();
//   return res;
// }

// async function task2() {
//   const res = await task1();
//   console.log("获取结果=", res);
// }

// task2();

/**
 * 实现
 */

function getData() {
  return fetch("https://sponsors.vuejs.org/data.json").then((res) => {
    return res.json().then((res) => res);
  });
}

function task1() {
  const res = getData();
  return res;
}

function task2() {
  const res = task1();
  console.log("获取结果=", res);
}
const _originalFetch = window.fetch;
function run() {
  const cache = [];
  let i = 0;
  window.fetch = (...args) => {
    const currentResult = cache[i];
    // 判读有没有缓存结果 有的话 返回结果
    if (currentResult) {
      // 判断结果的状态
      if (currentResult.stutas === "fulfilled") {
        return currentResult.data;
      } else if (currentResult.stutas === "rejected") {
        // 请求接口失败了 抛出错误
        throw currentResult.error;
      }
    }
    // 定义fetch请求结果
    const result = {
      stutas: "pending", //默认 pending
      data: null,
      error: null,
    };
    cache[i++] = result;
    // 发送fetch请求
    const prom = _originalFetch(...args)
      .then((res) => res.json())
      .then(
        (res) => {
          result.stutas = "fulfilled";
          result.data = res;
        },
        (err) => {
          result.stutas = "rejected";
          result.error = err;
        }
      );

    // 报错
    throw prom;

    // return prom;
  };
  // window.fetch().then();
  try {
    task2();
  } catch (error) {
    console.log("====捕获异常====", error);
    if (error instanceof Promise) {
      const reRun = () => {
        i = 0;
        task2();
      };
      error.then(
        () => {
          debugger;
          i = 0;
          task2();
        },
        () => {
          debugger;
          i = 0;
          task2();
        }
      );
    }
  }
}
run();
